<template>
	<van-cascader title="选择城市" :options="options" @close="complete" :closeable="false">
		<template #option="{ option }">
			<template v-if="!option.children || option.children.length === 0">
				<van-checkbox-group v-model="selectedValues" shape="square">
					<van-checkbox :name="option.value">
						{{ option.text }}
					</van-checkbox>
				</van-checkbox-group>
			</template>
			<template v-else>
				{{ option.text }}
			</template>
		</template>
	</van-cascader>
	<!-- 自定义确认按钮，替代默认的关闭图标 -->
	<div class="popup-footer">
		<van-button size="small">取消</van-button>
		<van-button size="small" type="primary" style="margin-left: 0.625rem;" @click="complete">确认</van-button>
	</div>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useCascaderAreaData } from '@vant/area-data';

	const emit = defineEmits<{
		closewindow : any
	}>();
	const props = defineProps({agreementType:String})
	const options = reactive([]);
	switch(props.agreementType){
		case '省级代理':
		useCascaderAreaData().forEach((item)=>{
			item.children = undefined;
			options.push(item);
		});
		break;
		case '城市代理':
		useCascaderAreaData().forEach((item)=>{
			item.children.forEach((citem)=>{
				citem.children = undefined;
			})
			options.push(item);
		});
		break;
		case '区县代理':
		useCascaderAreaData().forEach((item)=>{
			options.push(item);
		});
		break;
		default:
		console.log('协议类型不匹配')
	}

	
	const selectedValues = ref([]);

	const complete = () => {
		const scopeArray = [];
		for (let s of selectedValues.value) {
			scopeArray.push(findParentsByValue(options, s).join('-'));
		}
		emit('closewindow', scopeArray);
	}
	const findParentsByValue = (data : any, targetValue : string) => {
		for (const item of data) {
			if (item.value === targetValue) {
				return [item.text];
			}
			if (item.children) {
				const path = findParentsByValue(item.children, targetValue);
				if (path) {
					return [item.text, ...path];
				}
			}
		}
		return null;
	};
</script>

<style scoped>
	.popup-footer {
		display: flex;
		justify-content: right;
		padding: 16px;
	}

	.confirm-button {
		color: white;
	}
</style>